<?php
/**
 * 数据模型
 *
 * @version $Id$
 */
class ModelItem
{
	/**
	 * 取得某一天的列表
	 *
	 * @param date $date
	 */
	public function getList($date = null)
	{
		if (empty($date))
			$date = date('Y_m_d');

		///
		$dir = $this->_getCacheDir($date);
		$file = $dir . sprintf("%s.php", $date);
		if ( ! file_exists($file)) {
			$data = $this->_spider();
			$content = "<?php\r\n return " . var_export($data, true) . ';';
			file_put_contents($file, $content);
		} else
			$data = require($file);

		///
		return $data;
	}

	/**
	 * 取得缓存目录
	 *
	 * @param date $date
	 * @return array
	 */
	private function _getCacheDir($date)
	{
		///
		$tmp = explode('_', $date);
		unset($tmp[2]);

		/**
		 * @var $h HelperDir
		 */
		$h = App::h("Dir");
		$dir = CACHE_DIR . 'Items/' . implode('/', $tmp) . '/';
		$h->make($dir);

		return $dir;
	}

	/**
	 * 爬虫
	 *
	 * @return array
	 */
	private function _spider()
	{
		///
		App::v('htmldom', false);

		///
		$data = array();
		$html = file_get_html('http://www.fanhuan.com/');

		///
		$classes = array();
		$list = $html->find(".recom-class", 0)->find("a");
		foreach ($list as $a) {
			if (preg_match("/data-cat=\"(\d)\" class=\"\">(.*)\(/", $a->outertext, $m))
				$classes[intval($m[1])] = trim($m[2]);
		}

		///
		$list = $html->find("#recom_box", 0)->find("li");
		foreach ($list as $li) {
			$info = array();

			///
			preg_match("/<li class=\".*\" data-cat=\"(\d)\">/", $li->outertext, $m);
			$info['class'] = $classes[intval($m[1])];

			/// Desc
			$info['desc'] = $li->find("p[class=ware-info-described]", 0)->innertext;

			/// Price
			$info['price_now'] = $li->find("strong[class=now-price]", 0)->innertext;

			$info['price_cost'] = $li->find("span[class=cost-price]", 0)->innertext;

			/// Title && ID
			$a = $li->find("h4 a", 0);

			$info['title'] = $a->innertext;

			$tmp = parse_url($a->href);
			parse_str($tmp['query'], $tmp);
			$info['id'] = trim($tmp['itemid']);

			/// Image
			$img = $li->find(".ware-pic img", 0);
			preg_match("/this\.src=\(\'(.*)\'\)/", $img->onerror, $m);
			$info['image'] = trim($m[1]);

			///
			$data[] = $info;
		}

		return $data;
	}
}
